package com.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 39. 组合总和
 * 优化版本
 *
 * @author fy
 * @date 2022/4/28 21:35
 */
public class Solution39_1 {

    private List<List<Integer>> res;

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        res = new ArrayList<>();
        // 对数组提前排序
        Arrays.sort(candidates);
        combinationSum(candidates, target, 0, new ArrayList<>());
        return res;
    }

    private void combinationSum(int[] candidates, int target, int index, List<Integer> preList) {
        if (target == 0) {
            res.add(new ArrayList<>(preList));
        }
        for (int i = index; i < candidates.length; i++) {
            int candidate = candidates[i];
            // 到这个数的时候如果就已经小于0了, 那么后面的数都不用尝试了, 但是得保证当前数组是有序的
            if (target - candidate < 0) {
                break;
            }
            target -= candidate;
            preList.add(candidate);
            combinationSum(candidates, target, i, preList);
            preList.remove(preList.size() - 1);
            target += candidate;
        }
    }

}
